/**
 * 
 */
package com.etrans.web.gps.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: DateUtil.java<／p>
 * <p>Description: <／p>
 * <p>Copyright: Copyright (c) 2007<／p>
 * <p>Company: E-trans<／p>
 * 
 * @author R.Lao
 * @date 2017年6月13日
 * @time 上午8:59:08
 * @version 1.0
 */
public class DateUtil {

	/**
	 * 获取指定时间戳(毫秒格式)
	 */
	public static String getMillFormatDateTime(long _value) {
		return getMillFormatDateTime(new Date(_value));
	}

	/**
	 * 获取指定日期(毫秒格式)
	 */
	public static String getMillFormatDateTime(Date _value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
		return sdf.format(_value);
	}

	/**
	 *  根据秒获取时分
	 *  
	 * @param second 秒
	 * @return String
	 */
	public static String getHMBySecond(int second){
		if(second/3600>=1){
			int h = second/3600;
			int m = second%3600/60;
			int s = second%60;
			return ""+h+"时"+(m>0?""+m+"分":"")+(s>0?""+s+"秒":"");
		}else{
			int m = second%3600/60;
			int s = second%60;
			return m+"分"+(s>0?""+s+"秒":"");
		}
	}
	
	/**
	 * <title>getStringToDate</title>
	 * 
	 * @param date
	 * @return Date
     */
	public static Date getStringToDate(String date){
		try {
			if(null!=date){
				return DateUtil.getStrToDate(date);
			}else{
				return DateUtil.getPreviousDayDate();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * getDateToString
	 * 
	 * @param _value Date
	 * @param  formate  String
	 * @return String
     */
	public static String getDateToString(Date _value,String formate) {
		if(null==formate)formate="yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(formate);
		return sdf.format(_value);
	}
	/**
	 * getDateToString
	 * 
	 * @param _value Date
	 * @param  formate  String
	 * @return String
     */
	public static String getDateToString(Date _value) {
		return getDateToString(_value,null);
	}

	/**
	 * <p>
	 * 	Date转时间型String
	 * </p>
	 * 
	 * @param runTime Date
	 * @param formate String
	 * @return _value String
	 */
	public static String getDateTimeString(Date runTime,String formate) {
		if(null==formate)formate="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(formate);
		return sdf.format(runTime);
	}
	/**
	 * 获取某一天0点
	 * @param date 某一天日期
	 * @return 
	 */
	public static String getDayStart(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date) + " 00:00:00";
	}
	/**
	 * 获取某一天23点59分59秒
	 * @param date 某一天日期
	 * @return 
	 */
	public static String getDayEnd(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date) + " 23:59:59";
	}
	
	/**
	 * 本地时间转成mongo时间
	 * @param date	时间格式为yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static Date getISODate(String date){
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d = format.parse(date);
			//再加上8小时对应的毫秒数
			long rightTime = (long) (d.getTime()); 
			
			//把得到的新的时间戳再次格式化成时间的格式
			String newtime = format.format(rightTime);
			return format.parse(newtime);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 从long型日期转String类型
	 * 
	 * @param date
	 * @param formate
	 * @return String
	 */
	public static String getDateFromLong(long date,String formate){
		Date _date = new Date(date);
		if(null==formate)formate="yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(formate);
		return sdf.format(_date);
	}
	
	/**
	 * getDate 
	 * 
	 * @param _value
	 * @return
	 */
	public static Date getDate(Date _value) {
		String time = getDateTimeString(_value,null);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * <title>获取前一天的日期</title>
	 * <code>getPreviousDayDate("yyyy-MM-dd")</code>
	 *
	 * @return Date date
	 */
	public static Date getPreviousDayDate(){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		return date;
	}

	/**
	 * <title>获取前N天的日期</title>
	 * <code>getPreviousDayDate("yyyy-MM-dd")</code>
	 *
	 * @return Date date
	 */
	public static Date getPreviousDayDate(int pre){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -(pre)); //得到前一天
		Date date = calendar.getTime();
		return date;
	}

	/**
	 * getStrToDate
	 * @param dateString
	 * @return
	 * @throws ParseException
     */
	public static Date getStrToDate(String dateString) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(dateString);
		return  date;
	}

	  /**
     * 计算两个日期之间相差的秒数
     * @param startdate 较小的时间 
     * @param enddate 较大的时间 
     * @return 相差秒数 
     * @throws ParseException
     */
    public static int SecondsBetween(String starttime,String endtime)  {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startdate;
		try {
			startdate = sdf.parse(starttime);
			Date enddate = sdf.parse(endtime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(startdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(enddate);
			long time2 = cal.getTimeInMillis();
			long between_days = (time2 - time1) / 1000;
			return Integer.parseInt(String.valueOf(between_days));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	} 
    
 
    /**
     * 
     * @param starttime
     * @param endtime
     * @return
     */
    public static boolean isSameDate(String starttime,String endtime){
    	return starttime.subSequence(0, 10).equals(endtime.substring(0, 10)); 
    }
    
     public static  String getStandardDateStr(Date start) {

        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);

        
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(tempStart.getTime());
    }
    
    public static  List<String> getBetweenDates(Date start, Date end) {
        List<String> result = new ArrayList<String>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        tempStart.add(Calendar.DAY_OF_YEAR, 1);
        
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        if(sdf.format(start).equals(sdf.format(end))){
        	result.add(sdf.format(start));
        }else{
        	result.add(sdf.format(start));
            while (tempStart.before(tempEnd)) {
                result.add(sdf.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
            result.add(sdf.format(end));
        }
        
        return result;
    }
 	/**
	 * 
	 * @param dateString 字符日期格式
	 * @param format 转换的格式
	 * @return
	 * @throws ParseException
	 */
	public static Date getStrToDateFormat(String dateString,String format) throws ParseException {
		if(format==null){
			format="yyyy-MM-dd hh:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = sdf.parse(dateString);
		return date;
	}
	
	public static void main(String[] args) throws ParseException {
//		System.out.println(DateUtil.getStrToDate("2017-03-01"));
//		String dateStr = "2017-07-02 16:01:00";
//		String formate="yyyy-MM-dd HH:mm:ss";
//		Date gpstime = new SimpleDateFormat(formate).parse(dateStr);
//		System.out.println(compare(gpstime.getTime()));
//		String s = DateUtil.getHMBySecond(3600);
//		System.out.println(getDates("2017-08-20","2017-09-21"));
	}
	
	/**
	 * 比较时间是否在业务允许范围内
	 */
	@SuppressWarnings("deprecation")
	public static boolean compare(Date alarmTime){
		Date date = new Date();
		alarmTime.setMinutes(alarmTime.getMinutes() + 10);
		return alarmTime.after(date);
	}
	
	public static boolean compare(long time){
		return compare(new Date(time));
	}
	
	/**
	 * @category 获取给定时间段的每一天日期的格式化字符串
	 * @author RenweiWu
	 * @param startDate 开始日期  yyyy-MM-dd
	 * @param endDate 结束日期  yyyy-MM-dd
	 * @return  List<String> 日期格式化的String
	 */
	 public static List<String> getDates(String startDate,String endDate){  
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		  Date dBegin=null;  
		  Date dEnd=null;
			try {
				dBegin = sdf.parse(startDate);
				dEnd = sdf.parse(endDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		  List<String> StringDate = new ArrayList<String>(); 
		  StringDate.add(sdf.format(dBegin));
		  Calendar calBegin = Calendar.getInstance();  
		  calBegin.setTime(dBegin);  // 使用给定的 Date 设置此 Calendar 的时间  
		  Calendar calEnd = Calendar.getInstance();  
		  calEnd.setTime(dEnd);   // 使用给定的 Date 设置此 Calendar 的时间  
		  while (dEnd.after(calBegin.getTime())){    // 测试此日期是否在指定日期之后  
			   calBegin.add(Calendar.DAY_OF_MONTH, 1);  // 根据日历的规则，为给定的日历字段添加或减去指定的时间量  
			   StringDate.add(sdf.format(calBegin.getTime()));  
		  	}  
		  return StringDate;  
	 }
	 
	/**
	 * @category 获取给定年份的第几周的周一和 周日 
	 * @author RenweiWu
	 * @param year 年份
	 * @param week 第几周
	 * @return Map<String,Object>  key: Monday周一的日期;  Sunday周日的日期;  year传入的年份;  week传入的周数;
	 * @author RenweiWu
	 */
    public  static Map<String,Object> getYearAndWeekByDate(int year,int week) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式  
    	Map<String,Object> map = new HashMap<String,Object>();
		Calendar cald = Calendar.getInstance();
		cald.set(Calendar.YEAR, year); // 2016年
		cald.set(Calendar.WEEK_OF_YEAR,week); // 设置为2016年的第10周
		cald.set(Calendar.DAY_OF_WEEK, 2); // 1表示周日，2表示周一，7表示周六
		Date date = cald.getTime();
        Calendar cal = Calendar.getInstance();  
        cal.setTime(date);  
       //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了  
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天  
        if(1 == dayWeek) {  
            cal.add(Calendar.DAY_OF_MONTH, -1);  
        }  
        cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一  
        int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天  
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek()-day);//根据日历的规则，给当前日期减去星期几与一个星期第一天的差值   
        String imptimeBegin = sdf.format(cal.getTime());  
        map.put("Monday",imptimeBegin);
        cal.add(Calendar.DATE, 6);  
        String imptimeEnd = sdf.format(cal.getTime());  
        map.put("Sunday",imptimeEnd);
        map.put("year",year);
        map.put("week",week);
        return map;
   }  
    
	/**
	 * @category 获取给定月份   获得给定月份的所有周一的日期 
	 * @author RenweiWu
	 * @param day 年份-月份  (yyyy-MM)
	 * @return List<String> 给定月份的所有周一的日期
	 * @author RenweiWu
	 */
    public static List<String> getMonday(String day){ 
    	List<String> list = new ArrayList<String>();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); 
	    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");    
	    Date intdate = null;
		try {
			intdate = sdf.parse(day);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    Calendar calendar = new GregorianCalendar();
	    calendar.setTime(intdate);
	    int count = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	    sdf1.setLenient(false);
	    SimpleDateFormat sdf2 = new SimpleDateFormat("EEE");
	    for(int i = 1; i < count+1; i++){
	        try {
	            Date date = sdf1.parse(day + "-" + i);
	            if("星期一".equals(sdf2.format(date))){
	            	list.add(sdf1.format(date));
	            }
	        } catch (ParseException e) {
	        	e.printStackTrace();
	        }
	    }
	    return list;
    }
    
    /** 
    * 获得该月第一天 
    * @param year 
    * @param month 
    * @return 
    */  
    public static String getFirstDayOfMonth(int year,int month){  
            Calendar cal = Calendar.getInstance();  
            //设置年份  
            cal.set(Calendar.YEAR,year);  
            //设置月份  
            cal.set(Calendar.MONTH, month-1);  
            //获取某月最小天数  
            int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);  
            //设置日历中月份的最小天数  
            cal.set(Calendar.DAY_OF_MONTH, firstDay);  
            //格式化日期  
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
            String firstDayOfMonth = sdf.format(cal.getTime());  
            return firstDayOfMonth;  
        }  
      
    /** 
    * 获得该月最后一天 
    * @param year 
    * @param month 
    * @return 
    */  
    public static String getLastDayOfMonth(int year,int month){  
            Calendar cal = Calendar.getInstance();  
            //设置年份  
            cal.set(Calendar.YEAR,year);  
            //设置月份  
            cal.set(Calendar.MONTH, month-1);  
            //获取某月最大天数  
            int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);  
            //设置日历中月份的最大天数  
            cal.set(Calendar.DAY_OF_MONTH, lastDay);  
            //格式化日期  
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
            String lastDayOfMonth = sdf.format(cal.getTime());  
            return lastDayOfMonth;  
        }  
    
    public static Date getDate(String date){
    	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
    	Date day = null;
    	try {
			day = sd.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return day;
    }
}
